package com.qk.filter;

import com.qk.utils.CurrentUserHoler;
import com.qk.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
//@WebFilter("/*")
public class TokenFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        String uri = httpRequest.getRequestURI();
        if (uri.contains("/login")) {
            log.info("login放行");
            chain.doFilter(httpRequest, httpResponse);
            return;
        }
        String token = httpRequest.getHeader("token");
        if (token == null || token.isEmpty()) {
            log.info("token不存在");
            httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

        try {
            Claims claims = JwtUtils.parseToken(token);
            Integer id = claims.get("id", Integer.class);
            log.info("当前用户id为：{}", id);
            CurrentUserHoler.setCurrentUser(id);
        } catch (Exception e) {
            log.info("token解析失败");
            httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

        chain.doFilter(httpRequest, httpResponse);

        CurrentUserHoler.removeCurrentUser();
    }
}
